//  利用工厂模式
function axios(options = {}) {
  //  创建一个实例对象 然后
  const proto = createProto(options);
  Object.setPrototypeOf(request, proto);

  return request;
}

function createProto(options: {}) {
  const proto = Object.create(null);

  // 给他添加方法
  proto.interceptor = {
    response: () => {},
    request: () => {},
  };

  proto.base_options = options;

  return proto;
}

async function request(options = {}) {
  options = { ...request.base_options, ...options };

  //  请求拦截器
  request.interceptor.request(options);

  //  进行请求处理
  const res: any = await fetchData(options);
  //  响应拦截器, 并将处理之后的结果返回
  return request.interceptor.response(res) || res;
}

function fetchData(options: any = {}) {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: resolve,
      fail: reject,
    });
  });
}

request.get = (options: any = {}) => {
  options.method = "GET";
  return request(options);
};

request.post = (options: any = {}) => {
  options.method = "POST";
  return request(options);
};

export default axios;
